package com.dhp.bkOjjudgeservice.strategy;

import cn.hutool.json.JSONUtil;
import com.dhp.model.codesandbox.JudgeInfo;
import com.dhp.model.codesandbox.JudgeStrategyContext;
import com.dhp.model.dto.question.JudgeConfig;
import com.dhp.model.entity.Question;
import com.dhp.model.enums.JudgeInfoMessageEnum;


import java.util.List;

/**
 * 判题策略
 */
public class JudgeServiceStrategy {

    //需要judgeCase，judgeInfo 返回的questionSubmit
    public void doJudge(JudgeStrategyContext judgeStrategyContext){

        List<String> inputList = judgeStrategyContext.getInputList();
        List<String> exOutPutList = judgeStrategyContext.getOutputList();
        JudgeInfo judgeInfo = judgeStrategyContext.getJudgeInfo();
        List<String> outputList = judgeStrategyContext.getExecuteOutputList();
        Question question = judgeStrategyContext.getQuestion();
        //默认状态Accepted
        judgeInfo.setMessage(JudgeInfoMessageEnum.ACCEPTED.getValue());

        //执行输出与示例输入长度不等
        if (outputList.size() != inputList.size()){
            judgeInfo.setMessage(JudgeInfoMessageEnum.WRONG_ANSWER.getValue());
            judgeInfo.setErrorMessage("结果数量不对");
            return;
        }
        //对比输出和输出用例
        for (int i = 0 ; i < exOutPutList.size() ; i ++){
            if (!exOutPutList.get(i).equals(outputList.get(i))){
                judgeInfo.setMessage(JudgeInfoMessageEnum.WRONG_ANSWER.getValue());
                //记录出错的用例信息
                StringBuilder sb = new StringBuilder();
                sb.append("输入：").append(inputList.get(i)).append("\n")
                        .append("示例输出：").append(exOutPutList.get(i)).append("\n")
                        .append("实际输出：").append(outputList.get(i));
                judgeInfo.setTime(0L);
                judgeInfo.setMemory(0L);
                judgeInfo.setErrorMessage(sb.toString());
                return;
            }
        }
        //对比执行信息
        String judgeConfigStr = question.getJudgeConfig();
        JudgeConfig judgeConfig = JSONUtil.toBean(judgeConfigStr , JudgeConfig.class);
        if (judgeInfo.getTime() > judgeConfig.getTimeLimit()){
            judgeInfo.setMessage(JudgeInfoMessageEnum.TIME_LIMIT_EXCEEDED.getValue());
        }
        if (judgeInfo.getMemory() > judgeConfig.getMemoryLimit()){
            judgeInfo.setMessage(JudgeInfoMessageEnum.MEMORY_LIMIT_EXCEEDED.getValue());
        }

    }
}
